#处理单个视频
import os
import json
import time
def dress_single_video(single_dir_path,save_dir):
    #先获得两个m4s文件名称，视频文件名
    m4s_1,m4s_2,name=get_files_path_and_name(single_dir_path)
    # print(m4s_1,m4s_2,name)
    #确保保存结果的文件夹存在
    if not os.path.exists(save_dir):os.makedirs(save_dir)
    #将两个m4s都去掉前面9个0并保存到指定文件夹
    for m4s in [m4s_1,m4s_2]:
        sub_9_0_and_save(m4s,save_dir)
    #延迟一小段事件确保文件正常保存后再转换
    time.sleep(0.1)
    os.system("ffmpeg.exe -i "+os.path.join(save_dir,os.path.basename(m4s_1))+" -i "+\
        os.path.join(save_dir,os.path.basename(m4s_2))+" -codec copy "+\
        os.path.join(save_dir,"_".join(name.split(" ")))+".mp4 -loglevel quiet")
    time.sleep(0.1)
    os.remove(os.path.join(save_dir,os.path.basename(m4s_1)))
    os.remove(os.path.join(save_dir,os.path.basename(m4s_2)))
    return name

#获得两个m4s文件名称，视频文件名
def get_files_path_and_name(single_dir_path):
    #先获得两个m4s文件名称
    media_s=[]
    for file in os.listdir(single_dir_path):
        if file.split(".")[-1]=="m4s":
            media_s.append(single_dir_path+"/"+file)
    #再获得视频文件名
    info_path=os.path.join(single_dir_path,".videoInfo")
    content=None
    with open(info_path,"rb")as f:
        content=f.read()
    json_content=json.loads(content)
    #获得两个m4s文件名称，视频文件名返回
    return media_s[0],media_s[1],"p"+str(json_content["p"])+" "+json_content["title"]
def sub_9_0_and_save(src_file_path,dest_dir_path):
    with open(src_file_path,"rb")as f:
        content=f.read()
    content=content[9:]
    with open(os.path.join(dest_dir_path,src_file_path.split("/")[-1]),"wb")as f:
        f.write(content)
# video_list_path="./data"
# save_dir="result"
def dress_videos(video_list_path):
    save_dir=os.path.join(video_list_path,"..","result")
    if not os.path.exists(save_dir):os.makedirs(save_dir)
    for single_video_path in os.listdir(video_list_path):
        single_video_path=os.path.join(video_list_path,single_video_path)
        name=dress_single_video(single_video_path,save_dir)

    
def dress_a_video(single_video_path):
    save_dir=os.path.join(single_video_path,"..","result")
    if not os.path.exists(save_dir):os.makedirs(save_dir)
    dress_single_video(single_video_path,save_dir)
# run(video_list_path)
# single_video_path="./data/137818616"
# save_dir="result"
# dress_single_video(single_video_path,save_dir)


def assign_jobs(jobs,cpu_count):
    # print(jobs)
    job_count=len(jobs)
    sep=int(job_count/cpu_count)
    job_assigned=[]
    for i in range(cpu_count+1):
        job_assigned.append(jobs[i*sep:(i+1)*sep])
    job_assigned[-2]=job_assigned[-2]+job_assigned[-1]
    job_assigned=job_assigned[:-1]
    return job_assigned